#include "TcpServer.h"
#include "TcpConnection.h"

#include <iostream>
#include <boost/bind.hpp>
#include <tbb/tick_count.h>


using namespace boost::asio;
using namespace std;
using namespace tbb;


TcpServer::TcpServer(unsigned short port /* = 80 */, bool showStat /* = false */)
	: _acceptor(_ioService),
	  _newConnection(new TcpConnection(_ioService, _workManager)),
	  _pollFilter(_ioService, _workManager, showStat),
	  _showStat(showStat)
{
	_pipeline.add_filter(_pollFilter);
	_pipeline.add_filter(_workFilter);

	ip::tcp::endpoint endpoint(ip::tcp::v4(), port);

	_acceptor.open(endpoint.protocol());
	_acceptor.set_option(ip::tcp::acceptor::reuse_address(true));
	_acceptor.bind(endpoint);
	_acceptor.listen();

	StartAccept();
}

TcpServer::~TcpServer()
{
	delete _newConnection;
}

void TcpServer::HandleAccept(const boost::system::error_code &error)
{
	if (!error)
	{
		_newConnection->StartParsing();
		_newConnection = new TcpConnection(_acceptor.io_service(), _workManager);
		StartAccept();
	}
}

void TcpServer::Run()
{
	while (true)
	{
		_pipeline.run(2);
	}
}

void TcpServer::StartAccept()
{
	_acceptor.async_accept(_newConnection->getSocket(),
		boost::bind(&TcpServer::HandleAccept, this, placeholders::error));
}